package org.jeecgframework.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyFactoryRecordServiceI;
import org.jeecgframework.web.system.pojo.base.ZyFactoryRecordEntity;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyUpFactoryRecordCheckSnThread;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 出厂记录
 * @author ZhangYunlong
 * @date 2016-04-18 11:47:35
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyFactoryRecordController")
public class ZyFactoryRecordController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyFactoryRecordController.class);

	@Autowired
	private ZyFactoryRecordServiceI zyFactoryRecordService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 出厂记录列表 页面跳转
	 */
	@RequestMapping(params = "zyFactoryRecord")
	public ModelAndView zyFactoryRecord(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_factory_record/zyFactoryRecordList");
	}
	
	/**
	 * 出厂记录列表 datagrid 
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyFactoryRecordEntity zyFactoryRecord,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyFactoryRecordEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyFactoryRecord, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyFactoryRecordService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除出厂记录
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ZyFactoryRecordEntity zyFactoryRecord, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyFactoryRecord = systemService.getEntity(ZyFactoryRecordEntity.class, zyFactoryRecord.getId());
		message = "出厂记录删除成功";
		try{
			zyFactoryRecordService.delete(zyFactoryRecord);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "出厂记录删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
//	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
//	@ResponseBody
//	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
//		AjaxJson j = new AjaxJson();
//		List<ZyFactoryRecordEntity> excelList = zyFactoryRecordService.parseExcel(request);
//		Map<Integer, String> repeatMap = new HashMap<Integer, String>();
//		ZyFactoryRecordEntity factoryRecord;
//		List<ZyEquipmentSpareEntity> equipmentSpareList = zyFactoryRecordService.getList(ZyEquipmentSpareEntity.class);
//		boolean flag;
//		StringBuilder message = new StringBuilder();
//		for(int i = 0;i < excelList.size();i++){
//			flag = true;
//			factoryRecord = excelList.get(i);
//			for(int s = 0;s < equipmentSpareList.size();s++){ 
//				if(equipmentSpareList.get(s).getSn().equals(factoryRecord.getSerialNum())){
//					j.setSuccess(false);
//					message.append(factoryRecord.getSerialNum());
//					message.append(",");
//					flag = false;
//					repeatMap.put(i, factoryRecord.getSerialNum());
//					break;
//				}
//			}
//			if(flag){
//				zyFactoryRecordService.saveEquipmentSpare(factoryRecord);
//				break;
//			}
//		}
//		
//		zyFactoryRecordService.saveZyFactoryRecordHEntity(excelList);
//		
//		zyFactoryRecordService.saveZyFactoryRecordEntity(excelList);
//		
//		if(!message.toString().equals("")){
//			j.setSuccess(false);
//			message.append("在设备表中已经存在");
//			j.setMsg(message.toString());
//		}
////		j.setObj(repeatMap);
//		return j;	
//	}

	/**
	 * @author xiul
	 * 2016-6-24 下午3:09:22
	 * Description 跳转 上传出厂记录页面 
	 */
	@RequestMapping(params = "uploadFile")
	public ModelAndView uploadFile(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_factory_record/uploadFactoryRecord");
	}
	
	/**
	 * @author xiul
	 * 2016-6-24 下午3:20:41
	 * Description 上传保存文件 
	 */
	@ResponseBody
	@RequestMapping(params = "importExcel")
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
		FileBean fileBean = UploadFileUtil.UploadFile(request);
		ZyFileLogEntity fileLog  = new ZyFileLogEntity();
		fileLog.setBusinessType(StaticValue.IMPORT_FILE_FACTORY_RECORDER); //文件业务
		fileLog.setOldFileName(fileBean.getFileRealName());//文件原名
		fileLog.setNewFileName(fileBean.getFileName());//文件新名
		fileLog.setFilePath(fileBean.getSavePath());
		fileLog.setFileType("xlsx");
		fileLog.setStatus("0");
		systemService.save(fileLog);
		j.setObj(fileBean.getSavePath());
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-6-17 下午1:26:56
	 * Description 导入出厂记录，只对比SN 和保存记录到 设备表 
	 */
	@ResponseBody
	@RequestMapping(params = "checkExcel")
	public AjaxJson checkExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		boolean flag = true;
		String msg = "导入成功";
		System.out.println("进入 对比出厂记录SN action");
		long begin = System.currentTimeMillis();
		List<Map<String, Object>> factoryMapList = zyFactoryRecordService.parseExcel(request,j);
		List<Map<String, Object>> snMapList = systemService.findForJdbc("SELECT es.sn FROM zy_equipment_spare es");
		try {
			int maxUnit = 2000;
			int countRow = factoryMapList.size();
			if(countRow > maxUnit){
	    		int threadC = countRow % maxUnit > 0 ? countRow / maxUnit + 1 : countRow / maxUnit;
	    		System.out.println("threadC:" + threadC);
	    		System.out.println("snList:" + factoryMapList.size());
	    		ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadC);
	    		ArrayList<Future<String>> results = new ArrayList<Future<String>>();      
				for (int i = 0; i < threadC; i++) {
					int beginR = i == 0 ? 1 : i * maxUnit + 1;
					int endR = i == (threadC -1 ) ? countRow : beginR + maxUnit - 1 ;
		            results.add(exec.submit(new ZyUpFactoryRecordCheckSnThread(factoryMapList,snMapList,beginR,endR)));
				}
				do{
					for (Future<String> fs : results) {
						if (fs.isDone()) {
							if(StringUtil.isNotEmpty(fs.get())){
								msg = "SN：" + fs.get() + "，在设备表中已经存在";
								flag = false;
								break;
							}
						}
					}
				}while(exec.getCompletedTaskCount() < results.size() && flag);
				exec.shutdown();
			}else{
				String repeatSn = zyFactoryRecordService.checkSnRepeat(factoryMapList,snMapList, 0, factoryMapList.size() - 1);
				if(StringUtil.isNotEmpty(repeatSn)){
					flag = false;
					msg = "SN：" + repeatSn + "，在设备表中已经存在";
				}
			}
		} catch (Exception e) {
			flag = false;
			msg = "导入失败";
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		System.out.println("解析并比对 sn 完毕，用时："+(end - begin) / 1000 +"." + (end - begin) % 1000 +"秒");
		j.setMsg(msg);
		System.err.println(msg);
		j.setSuccess(flag);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-6-17 上午11:12:39
	 * Description 对比完SN之后 保存数据 
	 * @param filePath 上传的excel保存路径
	 */
	@ResponseBody
	@RequestMapping(params="readExcel")
	public void readExcel(@RequestParam(value="filePath")String filePath){
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>进入保存出厂记录数据 action");
		long begin = System.currentTimeMillis();
		zyFactoryRecordService.readExcel(filePath);
		long end = System.currentTimeMillis();
		System.out.println("保存出厂记录数据  用时："+(end - begin) / 1000 +"." + (end - begin) % 1000 +"秒");
	}
	
}
